<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-1-24
 * Time: 下午5:36
 */

namespace api\modules\chedai\controllers;


use common\components\tools\Tools;
use common\models\credit_app\OrderCert;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\helpers\ArrayHelper;

class GuarantorController extends Controller
{
    /**
     * 保存担保人签名照及视频
     * @desc post/get
     * @param json $ct_guarantor_detail 担保人
     * @return array
     */
    public function actionSaveGuarantorsSignAndVideo($ct_guarantor_detail)
    {
        $x = $ct_guarantor_detail;
        $x = json_decode($x);
        $x = ArrayHelper::toArray($x);
        if (!$x){
            throw new ErrorException('没有担保人!');
        }
        $r = [];
        $trans = \Yii::$app->db_app->beginTransaction();
        try{
            foreach ($x as $k => $v){
                $ct_key = $v['ct_key'];
                if ($ct_key != 'guarantor'){
                    throw new ErrorException("不能保存非担保人的数据!");
                }
                $oid = $v['ct_oid'];
                $id = $v['ct_id'];
                $model = OrderCert::findOne(['ct_id'=>$id, 'ct_oid'=>$oid, 'ct_key'=>$ct_key]);
                if (!$model){
                    throw new ErrorException("没有找到担保人!");
                }
                foreach ($model as $k1 => $v1){
                    if (isset($v[$k1])){
                        $model->$k1 = $v[$k1];
                        if (in_array($k1, ['ct_sign', 'ct_video'])){
                            $model->$k1 = Tools::str2arr($model->$k1);
                        }
                        if (in_array($k1, ['ct_attach', 'ct_detail', 'ct_sign', 'ct_video'])){
                            $model->$k1 = serialize($model->$k1);
                        }
                    }
                }
                if(!$model->save()){
                    throw new Exception('担保人保存异常!'.var_export($model->errors, true));
                };
                $r[] = $model->toArray();
            }
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
        \Yii::$app->response->statusText = '保存成功';
        return $r;
    }
}